import threading
import requests
from PySide6.QtCore import QTimer
from PySide6.QtWidgets import QWidget, QVBoxLayout, QHBoxLayout, QLabel, QLineEdit, QPushButton, QTextEdit

from database.database import get_database
from database.models import Config
from utils.send_email import send_mail
from utils.setting import main_info
from utils.setting import mail_text_service_error
from utils.log_recorder import setup_logger as logger


class ServicePage(QWidget):
    """启动服务页面"""

    def __init__(self, log_text_edit):
        super().__init__()  # 调用父类构造函数
        self.log_text_edit = log_text_edit  # 日志显示框
        self.api_url = ""  # 初始化后端API地址
        self.init_ui()  # 初始化UI
        self.service_timer = QTimer(self)  # 服务状态定时器
        self.service_timer.timeout.connect(self.check_service_status)  # 定时器超时连接到check_service_status函数
        self.load_api_url()  # 加载已保存的API地址

    def init_ui(self):
        layout = QVBoxLayout()

        # API输入框和保存按钮的水平布局
        input_layout = QHBoxLayout()
        self.api_input = QLineEdit()
        self.api_input.setPlaceholderText("请输入http://或https://开头的URL地址")
        input_layout.addWidget(self.api_input)

        self.save_button = QPushButton("保存")
        self.save_button.clicked.connect(self.save_api_url)
        input_layout.addWidget(self.save_button)

        layout.addWidget(QLabel("请输入API接口地址:"))  # 直接添加标签到垂直布局
        layout.addLayout(input_layout)

        # 启动服务和停止服务按钮的水平布局
        service_control_layout = QHBoxLayout()
        self.start_button = QPushButton("启动服务")
        self.start_button.clicked.connect(self.start_service_thread)
        service_control_layout.addWidget(self.start_button)

        self.stop_button = QPushButton("停止服务")
        self.stop_button.clicked.connect(self.stop_service_thread)
        service_control_layout.addWidget(self.stop_button)

        layout.addLayout(service_control_layout)

        # 服务状态显示
        self.status_label = QLabel("服务状态:")
        self.status_display = QTextEdit()
        self.status_display.setReadOnly(True)
        layout.addWidget(self.status_label)
        layout.addWidget(self.status_display)

        self.setLayout(layout)

    def start_service_thread(self):
        """启动服务的线程"""
        threading.Thread(target=self.start_service).start()  # 启动线程

    def stop_service_thread(self):
        threading.Thread(target=self.stop_service).start()

    def save_api_url(self):
        """保存后端API地址到数据库，用户点击保存按钮时调用"""

        try:
            api_url = self.api_input.text()
            if not api_url:
                self.log_text_edit.appendPlainText("请输入API接口地址")
                return

            database = get_database()
            logger().info(f"[servicePage-save_api_url]连接数据库成功")

            config_first = database.query(Config).first()  # 获取数据库中第一条记录

            if config_first:
                config_first.api_url = api_url  # 更新API地址
                database.commit()
                logger().info(f"[servicePage-save_api_url]更新API地址成功")
            else:
                new_config = Config(api_url=api_url)
                database.add(new_config)
                database.commit()
                logger().info(f"[servicePage-save_api_url]保存API地址成功")

            database.close()  # 关闭数据库连接
            logger().info(f"[servicePage-save_api_url]关闭数据库连接成功")

        except Exception as e:
            logger().error(f"[servicePage-save_api_url]保存API地址失败: {e}")

    def load_api_url(self):
        """从数据库加载已保存的API地址"""

        try:
            database = get_database()
            logger().info(f"[servicePage-load_api_url]连接数据库成功")

            config = database.query(Config).first()
            if config:
                self.api_input.setText(config.api_url)
                logger().info(f"[servicePage-load_api_url]加载API地址成功: {config.api_url}")
            else:
                logger().info(f"[servicePage-load_api_url]未找到API地址")

        except Exception as e:
            logger().error(f"[servicePage-load_api_url]加载API地址失败: {e}")

    def start_service(self):
        """启动服务"""
        self.api_url = self.api_input.text()
        if not self.api_url:
            self.log_text_edit.appendPlainText("请输入API接口地址")
            return

        self.log_text_edit.appendPlainText(f"尝试启动服务: {self.api_url}")
        try:
            response = requests.get(self.api_url)
            if response.status_code == 200:
                self.log_text_edit.appendPlainText("服务启动成功")
                self.status_display.append(f"服务已启动: {self.api_url}")
                self.service_timer.start(1000)  # 每秒检查一次服务状态
            else:
                self.log_text_edit.appendPlainText(f"服务启动失败: {response.status_code}")
                self.status_display.append(f"服务启动失败: {response.status_code}")
                send_mail(main_info,
                          mail_text={"subject": "服务启动失败", "message": f"服务启动失败: {response.status_code}"})
        except requests.exceptions.RequestException as e:
            self.log_text_edit.appendPlainText(f"服务启动失败: {e}")
            self.status_display.append(f"服务启动失败: {e}")
            send_mail(main_info, mail_text={"subject": "服务启动失败", "message": f"服务启动失败: {e}"})

    def stop_service(self):
        """停止服务"""
        self.log_text_edit.appendPlainText(f"尝试停止服务: {self.api_url}")
        try:
            response = requests.get(self.api_url + "/stop")  # 假设停止服务的API地址是 /stop
            if response.status_code == 200:
                self.log_text_edit.appendPlainText("服务停止成功")
                self.status_display.append(f"服务已停止: {self.api_url}")
                self.service_timer.stop()  # 停止定时器
            else:
                self.log_text_edit.appendPlainText(f"服务停止失败: {response.status_code}")
                self.status_display.append(f"服务停止失败: {response.status_code}")
                send_mail(main_info, mail_text={"subject": "服务停止失败", "message": f"服务停止失败: {response.status_code}"})
        except requests.exceptions.RequestException as e:
            self.log_text_edit.appendPlainText(f"服务停止失败: {e}")
            self.status_display.append(f"服务停止失败: {e}")
            send_mail(main_info, mail_text={"subject": "服务停止失败", "message": f"服务停止失败: {e}"})

    def check_service_status(self):
        """定时器超时函数，每秒检查一次服务状态"""
        try:
            response = requests.get(self.api_url)
            if response.status_code == 200:
                self.status_display.append("服务正在运行...")
            else:
                self.status_display.append(f"服务状态异常: {response.status_code}")
                send_mail(main_info, mail_text={"subject": "服务状态异常", "message": f"服务状态异常: {response.status_code}"})
                self.service_timer.stop()  # 停止定时器
        except requests.exceptions.RequestException as e:
            self.status_display.append(f"服务检查失败: {e}")
            send_mail(main_info, mail_text={"subject": "服务检查失败", "message": f"服务检查失败: {e}"})
            self.service_timer.stop()  # 停止定时器
